const express = require('express');
var User = require("../db/db.js");
var template = require("../template.js")
var pub = require("../public.js")

var router = express.Router();


// 学生首页
router.get('/', function(req, res) {
   res.render('index', {
        title: "首页-我图网"
    })
});


router.get('/login', function(req, res) {
    res.render('login', {
        title: "登录-我图网"
    })
});
router.get('/register', function(req, res) {
    res.render('register', {
        title: "注册-我图网"
    })
});


router.post('/api/login', function(req, res) {
   // console.log(req.body)
   var user = req.body;
   User.find({name:user.name},function(err,data){
     if (!err) {
            if (data.length > 0) {
            console.log(data[0])
             var isIn = (data[0].name == user.name && data[0].password == user.password)
             if (isIn) {
                 // user.id = data[0]._id;
                 res.status(200).json({code:"success",mess:"恭喜你！登录成功",data:user})
             }else {
                 res.status(200).json({code:"error",mess:"密码错误"})
             }
         }else {
              res.status(200).json({code:"null",mess:"此用户不存在，请先注册！"})
         }
     }
   })
});

router.post('/api/register', function(req, res) {
  console.log(req.body)
  var user = req.body
  if (user.password == user.password2) {
     delete user.password2
     console.log(user)
     User.find({name:user.name},function(err,data){
        if (!err) {
            console.log(data)
            if (data.length > 0) {
                res.status(200).json({code:"success",mess:"该用户已存在！"})
            }else {
                new User(user).save((err)=>{
                    if (err) {
                        res.status(200).json({code:"success",mess:"注册失败"})
                    }else {
                         res.status(200).json({code:"success",mess:"恭喜你！注册成功"})
                    }
                })
            }
        }
     })


  }else {
      res.status(200).json({code:"success",mess:"输入的密码不一致"})
  }
});




module.exports = router;
